package com.shuorikeji.huohuo.ui.fl;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdLoadType;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;
import com.bytedance.sdk.openadsdk.mediation.ad.MediationAdSlot;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsRewardVideoAd;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsVideoPlayConfig;
import com.luck.picture.lib.permissions.RxPermissions;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.ad.TxJlAdHelper;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.AdCountMainBean;
import com.shuorikeji.huohuo.bean.AdCountSubBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.common.Constant;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.ui.home.HomeActivity;
import com.shuorikeji.huohuo.ui.me.MyActivity;
import com.shuorikeji.huohuo.ui.sj.SjActivity;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.PreUtils;
import com.shuorikeji.huohuo.utils.ToastShowUtil;

import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class TaskGcActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_tab_1)
    LinearLayout llTab1;
    @BindView(R.id.ll_tab_2)
    LinearLayout llTab2;
    @BindView(R.id.ll_tab_3)
    LinearLayout llTab3;
    @BindView(R.id.ll_tab_4)
    LinearLayout llTab4;
    @BindView(R.id.tv_js_all_jd)
    TextView tvBookAdCount;
    @BindView(R.id.tv_js_all_see)
    TextView tvBookSeeAd;
    @BindView(R.id.tv_js_mh_jd)
    TextView tvMhAdCount;
    @BindView(R.id.tv_js_mh_see)
    TextView tvMhSeeAd;
    @BindView(R.id.tv_js_dj_see)
    TextView tvJsDjSee;

    private AdCountSubBean adCountBean;
    private TTRewardVideoAd mTTRewardVideoAd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_task_gc);
    }

    @Override
    protected void initData() {
        //getCommonTask();
        getSeeAdCount();
        initClick();
    }

    private void getCommonTask() {
        mPresenter.getAllReadSeeVideoCount(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getSeeAdCount() {
        mPresenter.getSeeAdCount(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        AdCountMainBean data = (AdCountMainBean) object;
                        adCountBean = data.getData();
                        if (adCountBean != null) {
                            tvBookAdCount.setText("小说当前完成进度：" + adCountBean.getNovelNum() + "/4");
                            tvMhAdCount.setText("漫画当前完成进度：" + adCountBean.getCartoonNum() + "/4");
                        }
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void sqCsjQx() {
        final String[] permissionsGroup = new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.READ_PHONE_STATE
                , Manifest.permission.ACCESS_WIFI_STATE
                , Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.ACCESS_COARSE_LOCATION};
        new RxPermissions(this)
                .request(permissionsGroup)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.i("wxl", "穿山甲广告权限申请状态：" + aBoolean);
                        if (aBoolean) {
                            csjAd(1);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void getBookAdJl() {
        mPresenter.getBookAdJl(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        getSeeAdCount();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void getMhAdJl() {
        mPresenter.getMhAdJl(true, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        getSeeAdCount();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void csjAd(int tag) {
        TTAdNative adNativeLoader = TTAdSdk.getAdManager().createAdNative(this);//需要传activity，切记！！！
        AdSlot adslot = new AdSlot.Builder()
                .setCodeId("103532932")
                .setOrientation(TTAdConstant.VERTICAL)//横竖屏设置
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .setMediationAdSlot(new MediationAdSlot
                        .Builder()
                        .build())
                .build();
        adNativeLoader.loadRewardVideoAd(adslot, new TTAdNative.RewardVideoAdListener() {
            @Override
            public void onError(int i, String s) {
                Log.e("wxl", "穿山甲广告错误：" + i + "===" + s);
            }

            @Override
            public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                mTTRewardVideoAd = ttRewardVideoAd;
                mTTRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {
                    @Override
                    public void onAdShow() {

                    }

                    @Override
                    public void onAdVideoBarClick() {

                    }

                    @Override
                    public void onAdClose() {

                    }

                    @Override
                    public void onVideoComplete() {

                    }

                    @Override
                    public void onVideoError() {

                    }

                    @Override
                    public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                    }

                    @Override
                    public void onRewardArrived(boolean isRewardValid, int rewardType, Bundle extraInfo) {
                        if (!isRewardValid) {
                            Log.d("wxl", "穿山甲广告发送奖励失败");
                            return;
                        } else {
                            if (tag == 1) {
                                getMhAdJl();
                            } else if (tag == 2) {

                            }
                        }
                    }

                    @Override
                    public void onSkippedVideo() {

                    }
                });
                mTTRewardVideoAd.showRewardVideoAd(TaskGcActivity.this);
            }

            @Override
            public void onRewardVideoCached() {

            }

            @Override
            public void onRewardVideoCached(TTRewardVideoAd ttRewardVideoAd) {
                mTTRewardVideoAd = ttRewardVideoAd;
                //可在该回调后进行广告展示
            }
        });
    }

    private void seeKsAd(long curDjTime) {
        KsScene.Builder builder = null;
        try {
            builder = new KsScene.Builder(Long.parseLong(Constant.KS_AD_ID));
            // 可选，跳转第三方应用后，配置返回响应页面;
            builder.setBackUrl("ksad://returnback");
            KsScene ksScene = builder.build();
            KsAdSDK.getLoadManager().loadRewardVideoAd(ksScene, new KsLoadManager.RewardVideoAdListener() {
                @Override
                public void onError(int i, String s) {
                    tvMhSeeAd.setEnabled(true);
                    tvMhSeeAd.setClickable(true);
                    ToastShowUtil.showToastCenter(TaskGcActivity.this, "快手广告失败：" + i + "===" + s);
                }

                @Override
                public void onRewardVideoResult(@Nullable List<KsRewardVideoAd> list) {
                    tvMhSeeAd.setEnabled(true);
                    tvMhSeeAd.setClickable(true);
                    if (list != null && list.size() > 0) {
                        PreUtils.put(Constant.KS_AD_SEE_TIME, curDjTime);
                        showKsAD(list.get(0));
                    } else {
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, "暂无快手广告");
                    }
                }

                @Override
                public void onRewardVideoAdLoad(@Nullable List<KsRewardVideoAd> list) {
                    tvMhSeeAd.setEnabled(true);
                    tvMhSeeAd.setClickable(true);
                }
            });
        } catch (Throwable e) {
            tvMhSeeAd.setEnabled(true);
            e.printStackTrace();
        }
    }

    private void showKsAD(KsRewardVideoAd ksRewardVideoAd) {
        ksRewardVideoAd.setRewardAdInteractionListener(new KsRewardVideoAd.RewardAdInteractionListener() {
            @Override
            public void onAdClicked() {

            }

            @Override
            public void onPageDismiss() {

            }

            @Override
            public void onVideoPlayError(int i, int i1) {

            }

            @Override
            public void onVideoPlayEnd() {
            }

            @Override
            public void onVideoSkipToEnd(long l) {

            }

            @Override
            public void onVideoPlayStart() {

            }

            @Override
            public void onRewardVerify() {

            }

            @Override
            public void onRewardVerify(Map<String, Object> map) {
                allSeeAdDy("快手", String.valueOf(ksRewardVideoAd.getECPM()));
                getMhAdJl();
            }

            @Override
            public void onRewardStepVerify(int i, int i1) {

            }

            @Override
            public void onExtraRewardVerify(int i) {

            }
        });
        ksRewardVideoAd.showRewardVideoAd(this, new KsVideoPlayConfig.Builder().showLandscape(false).build());
    }

    private void seeYlhAd(long curDjTime) {
        TxJlAdHelper txJlAdHelper = new TxJlAdHelper(TaskGcActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        //广告播放完成
                        PreUtils.put(Constant.YLH_AD_SEE_TIME, curDjTime);
                        tvBookSeeAd.setEnabled(true);
                        tvBookSeeAd.setClickable(true);
                        int ecpm = (int) object;
                        allSeeAdDy("优量汇", String.valueOf(ecpm));
                        getBookAdJl();
                        break;
                    case 2:
                        tvBookSeeAd.setEnabled(true);
                        tvBookSeeAd.setClickable(true);
                        break;
                }
            }
        });
        txJlAdHelper.showAd();
    }

    private void initClick() {
        llTab1.setOnClickListener(view -> {
            Intent intent = new Intent(TaskGcActivity.this, HomeActivity.class);
            startActivity(intent);
            finish();
        });
        llTab2.setOnClickListener(view -> {
            Intent intent = new Intent(TaskGcActivity.this, SjActivity.class);
            startActivity(intent);
            finish();
        });
        llTab4.setOnClickListener(view -> {
            Intent intent = new Intent(TaskGcActivity.this, MyActivity.class);
            startActivity(intent);
            finish();
        });
        tvBookSeeAd.setOnClickListener(view -> {
            if (adCountBean != null) {
                if (adCountBean.getNovelNum() < 4) {
                    //观看小说广告
                    long curDjTime = System.currentTimeMillis();
                    long lastDjTime = (long) PreUtils.get(Constant.YLH_AD_SEE_TIME, 0L);
                    if (lastDjTime == 0) {
                        tvBookSeeAd.setEnabled(false);
                        tvBookSeeAd.setClickable(false);
                        seeYlhAd(curDjTime);
                    } else {
                        if (BusinessUtils.longTimeSjc(curDjTime, lastDjTime) > 600) {
                            tvBookSeeAd.setEnabled(false);
                            tvBookSeeAd.setClickable(false);
                            seeYlhAd(curDjTime);
                        } else {
                            ToastShowUtil.showToastCenter(TaskGcActivity.this, "距上次观看广告不超过10分钟，请稍后再观看广告");
                        }
                    }
                } else {
                    ToastShowUtil.showToastCenter(TaskGcActivity.this, "已完成今日进度");
                }
            } else {
                ToastShowUtil.showToastCenter(TaskGcActivity.this, "暂无进度信息");
            }
        });
        tvMhSeeAd.setOnClickListener(view -> {
            if (adCountBean != null) {
                if (adCountBean.getCartoonNum() < 4) {
                    //观看漫画广告
                    //sqCsjQx();
                    long curDjTime = System.currentTimeMillis();
                    long lastDjTime = (long) PreUtils.get(Constant.KS_AD_SEE_TIME, 0L);
                    if (lastDjTime == 0) {
                        tvMhSeeAd.setEnabled(false);
                        tvMhSeeAd.setClickable(false);
                        seeKsAd(curDjTime);
                    } else {
                        if (BusinessUtils.longTimeSjc(curDjTime, lastDjTime) > 600) {
                            tvMhSeeAd.setEnabled(false);
                            tvMhSeeAd.setClickable(false);
                            seeKsAd(curDjTime);
                        } else {
                            ToastShowUtil.showToastCenter(TaskGcActivity.this, "距上次观看广告不超过10分钟，请稍后再观看广告");
                        }
                    }
                } else {
                    ToastShowUtil.showToastCenter(TaskGcActivity.this, "已完成今日进度");
                }
            } else {
                ToastShowUtil.showToastCenter(TaskGcActivity.this, "暂无进度信息");
            }
        });
        tvJsDjSee.setOnClickListener(view -> {
            csjAd(2);
        });
    }

    private void allSeeAdDy(String sdkName, String ecpm) {
        mPresenter.allSeeAdDy(false, "coin_look_video2", ecpm, 2, sdkName, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(TaskGcActivity.this, msg);
                        break;
                }
            }
        });
    }
}